package com.example.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.feignapi.article.ArticleClient;
import com.example.feignapi.schedule.ScheduleClient;
import com.example.model.article.dto.ArticleDto;
import com.example.model.schedule.dto.TaskDto;
import com.example.model.wemedia.pojo.Channel;
import com.example.model.wemedia.pojo.News;
import com.example.model.wemedia.pojo.User;
import com.example.utils.common.ProtostuffUtil;
import com.example.wemedia.mapper.ChannelMapper;
import com.example.wemedia.mapper.NewsMapper;
import com.example.wemedia.mapper.UserMapper;
import com.example.wemedia.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Autowired
    private ScheduleClient scheduleClient;
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private NewsAutoScanServiceImpl newsAutoScanService;

    @Override
    public boolean addTask(News news) {
        TaskDto taskDto = new TaskDto();
        taskDto.setTaskType(200);
        taskDto.setPriority(1);
        taskDto.setExecuteTime(news.getPublishTime());

        taskDto.setParameters("" + news.getNewsId());

        R r = scheduleClient.addTask(taskDto);
        log.info("添加定时任务结果：{}", r.toString());
        if (r.getCode() == ResultCodeRecord.SUCCESS.code())  {
            return r.getData().isEmpty();
        }
        return false;
    }

    @Scheduled(cron = "0 0 0/5 * * ?")
    public void pollTask() {
        R r = scheduleClient.pollTask(20, 1);
        log.info("获取定时任务结果：{}", r.toString());

        if (r.getCode() != ResultCodeRecord.SUCCESS.code() || r.getData() == null)  {
            return;
        }
        String jsonString = JSON.toJSONString(r.getData());
        TaskDto taskDto = JSON.parseObject(jsonString, TaskDto.class);
        News news = ProtostuffUtil.deserialize(taskDto.getParameters().getBytes(), News.class);
        // 一定要重新查询一次，因为我们添加到任务里面有id
        News news1 = newsMapper.selectById(news.getNewsId());
        newsAutoScanService.autoScan(news);
    }
}
